import UserModel from "@/model/User"

class User{
    
    public async regist(ctx,next) {
        const params = ctx.request.body;
        if(!params.username || !params.password || !params.confirmPassword){
            ctx.body = {
                code: 400,
                message: "缺少参数"
            };
            return;
        }else{
            if(params.password!== params.confirmPassword){
                ctx.body = {
                    code: 400,
                    message: "两次密码不一致"
                };
                return;
            }
        }

    
        try {
            
           await UserModel.create({
                username: params.username,
                password: params.password
            })
            ctx.body = {
                code: 200,
                message: "注册成功"
            };
         
        } catch (error) {
            ctx.body = {
                code: 400,
                message: "注册失败"
            };
        }
        


    }

    public async login(ctx,next){
        const params = ctx.request.body;
        if(!params.username ||!params.password){
            ctx.body = {
                code: 400,
                message: "缺少参数"
            };
            return;
        }

       try {
        const user = await UserModel.findOne({
            where: {
                username: params.username
            }
        })
        if(user){
               
            if(user.dataValues.password === params.password){
        
                ctx.body = {
                    code: 200,
                    message: "登录成功",
                    data: user.dataValues.user_id
                };
            }else{
                ctx.body = {
                    code: 400,
                    message: "密码错误"
                };
            }
        }else{
            ctx.body = {
                code: 400,
                message: "用户不存在"
            };
        }
       } catch (error) {
        ctx.body = {
            code: 400,
            message: "服务器错误"
        }
       }
    }
}

export default User;